package cn.edu.njupt.post.controller;

import cn.edu.njupt.post.model.HostHolder;
import cn.edu.njupt.post.model.Message;
import cn.edu.njupt.post.model.User;
import cn.edu.njupt.post.model.ViewObject;
import cn.edu.njupt.post.service.MessageService;
import cn.edu.njupt.post.service.UserService;
import cn.edu.njupt.post.util.JedisAdapter;
import cn.edu.njupt.post.util.OtherUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping({"/msg"})
public class MessageController {
    private static final Logger logger = LoggerFactory.getLogger(JedisAdapter.class);

    @Autowired
    MessageService messageService;

    @Autowired
    UserService userService;

    @Autowired
    HostHolder hostHolder;

    @RequestMapping(path = {"/list", "/", ""}, method = {RequestMethod.GET})
    public String conversationDetail(Model model,
                                     @RequestParam(value = "pId", defaultValue = "1") int pId) {
        try {
            int localUserId = hostHolder.getUser().getId();
            List<ViewObject> conversations = new ArrayList<ViewObject>();

            List<Message> conversationList = messageService.getConversationList(localUserId, (pId - 1) * 10, 10);

            for (Message msg : conversationList) {
                ViewObject vo = new ViewObject();
                vo.set("conversation", msg);

                vo.set("fromUser", userService.getUser(msg.getFromId()));
                vo.set("toUser", userService.getUser(msg.getToId()));
                vo.set("unread", messageService.getConversationUnreadCount(localUserId, msg.getConversationId()));
                conversations.add(vo);



            }
            model.addAttribute("conversations", conversations);

            int lastPage = messageService.getConversationCount(localUserId);
            lastPage = lastPage / 10 + ((lastPage % 10 == 0) ? 0 : 1);
            if (0 < pId && pId < lastPage) model.addAttribute("nextPId", pId + 1);
            if (1 < pId && pId <= lastPage) model.addAttribute("prePId", pId - 1);
        } catch (Exception e) {
            logger.error("获取站内信列表失败" + e.getMessage());
        }
        return "letter";
    }

    @RequestMapping(path = {"/detail"}, method = {RequestMethod.GET})
    public String conversationDetail(Model model, @RequestParam("conversationId") String conversationId,
                                     @RequestParam(value = "pId", defaultValue = "1") int pId) {
        //别人查看？
        try {
            List<Message> conversationList = messageService.getConversationDetail(conversationId, 10 * (pId - 1), 10);
            List<ViewObject> messages = new ArrayList<>();
            for (Message msg : conversationList) {
                ViewObject vo = new ViewObject();
                vo.set("message", msg);
                User user = userService.getUser(msg.getFromId());
                if (user == null) {
                    continue;
                }
                vo.set("fromUser", user);
                messages.add(vo);

                if (msg.getToId() == hostHolder.getUser().getId()) {
                    messageService.updateUnread(msg.getToId(), msg.getConversationId());
                }
            }
            model.addAttribute("messages", messages);

            int lastPage = messageService.getDetailCount(conversationId);
            lastPage = lastPage / 10 + ((lastPage % 10 == 0) ? 0 : 1);
            if (0 < pId && pId < lastPage) model.addAttribute("nextPId", pId + 1);
            if (1 < pId && pId <= lastPage) model.addAttribute("prePId", pId - 1);
            model.addAttribute("conversationId", conversationId);
        } catch (Exception e) {
            logger.error("获取详情消息失败" + e.getMessage());
        }
        return "letter_detail";
    }


    @RequestMapping(path = {"/add"}, method = {RequestMethod.POST})

    public String addMessage(@RequestParam("to_id") int toId,
                             @RequestParam("content") String content) {
        try {
            if (hostHolder.getUser() == null) {
                //return OtherUtil.getJSONString(999, "未登录");
                return "redirect:/reglogin";
            }
            User toUser = userService.getUser(toId);
            if (toUser == null) {
                //return OtherUtil.getJSONString(1, "用户不存在");
                return "redirect:/";
            }

            Message msg = new Message();
            int fromId = hostHolder.getUser().getId();
            msg.setContent(content)
                    .setFromId(fromId)
                    .setToId(toId)
                    .setCreatedDate(new Date())
                    .setConversationId(fromId < toId ? String.format("%d_%d", fromId, toId) : String.format("%d_%d", toId, fromId));
            messageService.addMessage(msg);
            //return OtherUtil.getJSONString(0);
        } catch (Exception e) {
            logger.error("增加站内信失败" + e.getMessage());
            //return OtherUtil.getJSONString(1, "插入站内信失败");
        }
        return "redirect:/user/" + toId;
    }


//    @RequestMapping(path = {"/jsonAddMessage"}, method = {RequestMethod.POST})
//    @ResponseBody
//    public String addMessage(@RequestParam("fromId") int fromId,
//                             @RequestParam("toId") int toId,
//                             @RequestParam("content") String content) {
//        try {
//            Message msg = new Message();
//            msg.setContent(content);
//            msg.setFromId(fromId);
//            msg.setToId(toId);
//            msg.setCreatedDate(new Date());
//            //msg.setConversationId(fromId < toId ? String.format("%d_%d", fromId, toId) : String.format("%d_%d", toId, fromId));
//            messageService.addMessage(msg);
//            return OtherUtil.getJSONString(msg.getId());
//        } catch (Exception e) {
//            //logger.error("增加评论失败" + e.getMessage());
//            return OtherUtil.getJSONString(1, "插入评论失败");
//        }
//    }
}
